package Sys_Module;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Calendar;

public class Worker_Window {
    private String[][] windows = new String[5][2]; // 窗口数组 【表示1-5窗口】 【状态：idle/init/work/done】 done 废弃
    private Server_Network SN48003; // 定义Server_Network的窗口机48003类的指针
    private Log_Module Log_Sys; // 定义Log系统的指针
    private int num_idle = 5, num_work = 0; // 定义窗口的变量 用于idle的数量，work数量的统计

    Worker_Window(Server_Network SN, Log_Module Log_Sys, boolean Data_Restore_mode) {
        try {
            Log_Sys.Write_log("Worker_Window info", "初始化工作窗口类");
        } catch (IOException e) {
        }
        for (int a = 0; a <= 4; a++) {
            for (int b = 0; b <= 1; b++) {
                if (b == 1) {
                    windows[a][1] = "idle";// 初始化windows数组 遍历数组 状态改为idle
                }
            }
        }
        Worker_INIT(Data_Restore_mode);
        this.Log_Sys = Log_Sys;// 传递指针
        this.SN48003 = SN;// 传递指针
    }

    private void Worker_INIT(boolean Data_Restore_mode) {
        if (Data_Restore_mode == true) {

            String WorkerData = "";
            try {
                WorkerData = Cache_Read_IN("Work_List");
                System.out.println(WorkerData);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (WorkerData != "") {
                WorkList_restore_data(WorkerData);
            }
        }

    }

    public synchronized int Window_status(int num) {// 获取窗口的状态 num传递窗口号 返回状态码
        String temp = "";
        temp = windows[num - 1][1];// 变量临时存储状态(字符串)
        if (temp.equals("idle")) {
            return 0;
        } else if (temp.equals("init")) {
            return 1;
        } else if (temp.equals("work")) {
            return 2;
        } // else if (temp.equals("done")) {
          // return 3;
          // }
        return 0;
    }

    public synchronized void Put_IN_Windows(int num, int wnum) // 第一个num是单号 第二个num是窗口号
    {
        windows[wnum - 1][0] = String.valueOf(num);
        Change_Windows_Status(wnum, 1);
    }

    public synchronized void Change_Windows_Status(int wnum, int status) // wnum指的是窗口号
    {
        String old_statusString = windows[wnum - 1][1]; // 用于存储窗口的旧状态 用于下面的日志存储
        switch (status) {
            case 1:
                windows[wnum - 1][1] = "init";
                num_idle--;// idle窗口数量减一
                num_work++;// work窗口数量加一
                break;
            case 2:
                windows[wnum - 1][1] = "work";
                break;
            // case 3:
            // windows[wnum - 1][1] = "done";
            // break;
            case 0:
                windows[wnum - 1][1] = "idle";
                num_idle++;// idle窗口数量加一
                num_work--;// work窗口数量减一
                break;
            default:
                windows[wnum - 1][1] = "empty";
                break;
        }
        try {
            Log_Sys.Write_log("Worker_Windows_Status",
                    "窗口" + wnum + ":旧状态:" + old_statusString + " 新状态:" + windows[wnum - 1][1] + " 工作空闲窗口数:"
                            + Get_Windows_Status_NUM(1) + " 工作繁忙窗口数:"
                            + Get_Windows_Status_NUM(2)); // 输出窗口改变的日志
        } catch (IOException e) {
        }
        SN48003.output("info#" + wnum + "$" + status); // 类型(info/request/response)#窗口(1-5)$信息

    }

    public String Display_All_Windows() {// 用于显示每个窗口的状态
        String temp = "";
        for (int a = 0; a <= 4; a++) {
            temp = temp + (a + 1) + "号窗口:" + windows[a][0] + "状态:" + windows[a][1] + " ";
        }
        return temp;
    }

    public String OutputData_All_Windows() {// 用于显示每个窗口的状态
        String outputdata = "";
        for (int a = 0; a <= 4; a++) {
            outputdata = outputdata + (a + 1) + "#" + windows[a][0] + "#" + windows[a][1] + ",";
        }
        return outputdata.substring(0, outputdata.length() - 1);
    }

    public int Get_Windows_Status_NUM(int lx) {// 获取窗口的idle数量或work数量 参数为1为idle 参数为2为work
        switch (lx) {
            case 1:
                return num_idle;
            case 2:
                return num_work;
        }
        return 0;
    }

    // 以下添加断电重启功能

    private static String Cache_getlujin() {// 获取路径程序
        File directory = new File("");// 设定为当前文件夹
        String text = "";
        try {
            // System.out.println(directory.getCanonicalPath());// 获取标准的路径
            text = directory.getAbsolutePath();// 获取绝对路径
        } catch (Exception e) {
        }
        return text + "\\cache\\";
    }

    private String Cahce_Get_File_Name(String name) throws IOException {
        Calendar ca_data = Calendar.getInstance(); // 初始化对象
        String temp; // 临时变量

        temp = name + " " + String.valueOf(ca_data.get(Calendar.YEAR)) + "-"
                + String.valueOf(ca_data.get(Calendar.MONTH) + 1) + "-" + String.valueOf(ca_data.get(Calendar.DATE))
                + ".cache";// 输出当前期
        File temp_file = new File(temp);
        if (temp_file.exists() == false) { // 检测文件是否存在
            temp_file.createNewFile(); // 如果文件不存在则创建
        }
        return temp;
    }

    private synchronized void Cache_Write_IN(String name, String data) throws IOException {

        String filename = Cahce_Get_File_Name(Cache_getlujin() + name);
        FileWriter cache_file_writer = null; // 新建writer file对象
        BufferedWriter cache_Buff_writer = null; // 新建buff writer 对象

        try {
            cache_file_writer = new FileWriter(filename, false); // 第二个参数为true 允许对日志文件的续写
        } catch (IOException e) {
            e.printStackTrace();
        }
        cache_Buff_writer = new BufferedWriter(cache_file_writer);
        cache_Buff_writer.flush();
        cache_Buff_writer.write(data);
        cache_Buff_writer.close();
        cache_file_writer.close();
    }

    private synchronized String Cache_Read_IN(String name) throws IOException {
        String temp = "", temp2 = "";
        String filename = Cahce_Get_File_Name(Cache_getlujin() + name);
        FileReader cache_file_reader = null; // 新建reader file对象
        BufferedReader cache_Buff_reader = null; // 新建buff reader 对象
        try {
            cache_file_reader = new FileReader(filename);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        cache_Buff_reader = new BufferedReader(cache_file_reader);

        while ((temp = cache_Buff_reader.readLine()) != null) {
            temp2 = temp2 + temp;
        }
        cache_Buff_reader.close();
        cache_file_reader.close();
        return temp2;

    }

    private void WorkList_restore_data(String data) {
        String[] format_data = data.split(",");
        // int i = 0;
        // System.out.println(OutputData_All_Windows());
        for (String ii : format_data) {
            System.out.println(ii);
            String[] format_data2 = ii.split("#");
            windows[Integer.valueOf(format_data2[0]) - 1][0] = format_data2[1];
            windows[Integer.valueOf(format_data2[0]) - 1][1] = format_data2[2];

        }
        // System.out.println(OutputData_All_Windows());
    }

}
